//
//  LYStocksManager.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/19.
//

import Foundation
import UIKit

class LYStocksManager {

    typealias Complation<T> = (T?, String, String?) -> Void
    static func fetchEnvironment(_ complation: Complation<HttpEnvironment>?) {
        let parameters: [String: Any] = [
            "thatage": "0",
            "quartar": "0",
            "networkdom": "en"
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/stillless",
            method: .post,
            parameters: parameters
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<HttpEnvironment>.self, from: data)
                    DispatchQueue.main.async {
                        guard let environment = response.myx else {
                            complation?(nil, response.motherling, "failed")
                            return
                        }
                        complation?(environment, response.motherling, nil)
                        print("获取环境成功: \(String(describing: environment.diploon))")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(nil, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取环境失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(nil, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    static func fetchMotherling(_ complation: Complation<HomeListData>?) {
        let parameters: [String: Any] = [
            "plyee": RandomStringGenerator.generate()
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/motherling",
            method: .get,
            parameters: parameters
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<HomeListData>.self, from: data)
                    DispatchQueue.main.async {
                        guard let homeListData = response.myx else {
                            complation?(nil, response.motherling, "failed")
                            return
                        }
                        complation?(homeListData, response.motherling, nil)
                        print("获取首页数据成功: \(String(describing: homeListData.guttality))")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(nil, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取首页数据失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(nil, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    static func fetchVerificationCode(phoneNumber: String, _ complation: Complation<VerificationCodeModel>?) {
        let parameters: [String: Any] = [
            "luctradeorium": phoneNumber,
            "help": RandomStringGenerator.generate(),
            "tooization": RandomStringGenerator.generate()
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/luctradeorium",
            method: .post,
            parameters: parameters
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<VerificationCodeModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let verificationCodeModel = response.myx else {
                            complation?(nil, response.motherling, "failed")
                            return
                        }
                        complation?(verificationCodeModel, response.motherling, nil)
                        print("获取验证码成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(nil, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取验证码失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(nil, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    static func fetchOrderList(orderListSelect: OrderListSelect, _ complation: Complation<OrderListData>?) {
        let parameters: [String: Any] = [
            "monyaneity": orderListSelect.rawValue,
            "paperous": "1",
            "lexally": "50"
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/obsless",
            method: .post,
            parameters: parameters
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<OrderListData>.self, from: data)
                    DispatchQueue.main.async {
                        guard let orderListData = response.myx else {
                            complation?(nil, response.motherling, "failed")
                            return
                        }
                        complation?(orderListData, response.motherling, nil)
                        print("获取订单列表成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(nil, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取订单列表失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(nil, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    static func fetchFollowUpOnOrderNumber(onomit: Onomit, _ complation: Complation<OrderFollowData>?) {
        let parameters: [String: Any] = [
            "wayent": onomit.backable ?? "",
            "aever": onomit.aever ?? "",
            "first": onomit.first ?? "",
            "testarium": onomit.testarium ?? "",
            "woman": RandomStringGenerator.generate(),
            "himself": RandomStringGenerator.generate()
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/receiveer",
            method: .post,
            parameters: parameters
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<OrderFollowData>.self, from: data)
                    DispatchQueue.main.async {
                        guard let followData = response.myx else {
                            complation?(nil, response.motherling, "failed")
                            return
                        }
                        complation?(followData, response.motherling, nil)
                        print("跟进订单成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(nil, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("跟进订单失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(nil, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    static func fetchLogin(phoneNumber: String, code: String, _ complation: Complation<LoginModel>?) {
        let parameters: [String: Any] = [
            "pravard": phoneNumber,
            "myress": code,
            "agoety": RandomStringGenerator.generate(),
            "makeid": RandomStringGenerator.generate()
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/tooization",
            method: .post,
            parameters: parameters
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<LoginModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let loginModel = response.myx else {
                            complation?(nil, response.motherling, "failed")
                            return
                        }
                        complation?(loginModel, response.motherling, nil)
                        
//                        LYUserDefaults.shared.set(phoneNumber, forKey: phoneNumKey)
//                        LYUserDefaults.shared.set(loginModel.finallyator, forKey: userSessionIdKey)
                        print("登录成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(nil, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("登录失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(nil, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    static func fetchLoginOut(_ complation: Complation<Bool>?) {
        let parameters: [String: Any] = [
            "vivation": RandomStringGenerator.generate(),
            "fastability": RandomStringGenerator.generate()
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/dipsiaization",
            method: .get,
            parameters: parameters
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<LoginModel>.self, from: data)
                    DispatchQueue.main.async {
                        complation?(true, response.motherling, nil)
                        print("退出登录成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(false, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("退出登录失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(false, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    static func fetchAccountCancellation(_ complation: Complation<Bool>?) {
        let parameters: [String: Any] = [
            "onia": RandomStringGenerator.generate()
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/billionuous",
            method: .get,
            parameters: parameters
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<LoginModel>.self, from: data)
                    DispatchQueue.main.async {
                        complation?(true, response.motherling, nil)
                        print("注销账号成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(false, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("注销账号失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(false, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    static func fetchProductApplyTo(productId: Int, _ complation: Complation<ProductApplyTo>?) {
        let parameters: [String: Any] = [
            "radinextics": "1001",
            "teachuous": "1000",
            "electionent": "1000",
            "caulithoughose": productId,
            "policanyaneity": RandomStringGenerator.generate()
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/agoety",
            method: .post,
            parameters: parameters
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<ProductApplyTo>.self, from: data)
                    DispatchQueue.main.async {
                        guard let productData = response.myx else {
                            complation?(nil, response.motherling, "failed")
                            return
                        }
                        complation?(productData, response.motherling, nil)
                        print("点击申请成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(nil, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("点击申请失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(nil, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    static func fetchProductDetail(productId: Int, _ complation: Complation<ProductData>?) {
        let parameters: [String: Any] = [
            "caulithoughose": productId,
            "vapite": RandomStringGenerator.generate()
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/makeid",
            method: .post,
            parameters: parameters
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<ProductData>.self, from: data)
                    DispatchQueue.main.async {
                        guard let productData = response.myx else {
                            complation?(nil, response.motherling, "failed")
                            return
                        }
                        complation?(productData, response.motherling, nil)
                        print("获取产品详情成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(nil, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取产品详情失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(nil, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    static func fetchCardischoolalityInfo(productId: Int, _ complation: Complation<CardData>?) {
        let parameters: [String: Any] = [
            "caulithoughose": "\(productId)",
            "ting": RandomStringGenerator.generate()
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/cardischoolality",
            method: .get,
            parameters: parameters
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<CardData>.self, from: data)
                    DispatchQueue.main.async {
                        guard let cardData = response.myx else {
                            complation?(nil, response.motherling, "failed")
                            return
                        }
                        complation?(cardData, response.motherling, nil)
                        print("获取用户身份信息成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(nil, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取用户身份信息失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(nil, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    enum ImageType: String { // 类型 10:人像,11身份证正面 12:身份证反面 20:签名照上传
        case unKnown = "-1"
        case portrait = "10"
        case frontID = "11"
        case reverseID = "12"
        case signedPhotograph = "20"
    }
    
    enum ImageSource: String { // 图片来源:1相册 2:拍照上传
        case album = "1"
        case camera = "2"
    }
    
    static func uploadImage(imageData: Data, imageType: ImageType, imageSource: ImageSource, _ complation: Complation<UploadIDCardData>?) {
        var parameters: [String: String] = [:]
        
//        if appCountryEnv == .indonesia {
//            parameters = [
//                "storyitious": imageType.rawValue,
//                "flammess": imageSource.rawValue,
//                "churchature": "",
//                "kino": "1",
//                "theri": RandomStringGenerator.generate()
//            ]
//        } else {
            parameters = [
                "storyitious": imageType.rawValue,
                "flammess": imageSource.rawValue,
                "churchature": ""
            ]
//        }
        
        NetworkManager.shared.uploadMultipart(domain: .api,
                                              path: "/plan/repling",
                                              parameters: parameters,
                                              fileData: imageData,
                                              fileName: "test.jpg",
                                              mimeType: "image/jpeg")  { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<UploadIDCardData>.self, from: data)
                    DispatchQueue.main.async {
                        guard let cardData = response.myx else {
                            complation?(nil, response.motherling, "failed")
                            return
                        }
                        complation?(cardData, response.motherling, nil)
                        print("身份证图片上传成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(nil, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("身份证图片上传失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(nil, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    static func fetchSaveCardInfo_yinNi(birthday: String,
                                        identifyNum: String,
                                        name: String,
                                        phoneNum: String,
                                        orderNum: String,
                                        productId: Int,
                                        _ complation: Complation<Bool>?) {
        let parameters: [String: Any] = [
            "monyry": RandomStringGenerator.generate(),
            "plut": RandomStringGenerator.generate(),
            "agohood": birthday,
            "typo": identifyNum,
            "sarcling": name,
            "forgetence": phoneNum,
            "wayent": orderNum,
            "caulithoughose": "\(productId)"
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/knowsome",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<NetworkManager.Temp>.self, from: data)
                    DispatchQueue.main.async {
                        complation?(true, response.motherling, nil)
                        print("保存用户身份信息成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(true, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("保存用户身份信息失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(false, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    static func fetchSaveCardInfo_yinDu(birthday: String,
                                        identifyNum: String,
                                        name: String,
                                        _ complation: Complation<Bool>?) {
        let parameters: [String: Any] = [
            "agohood": birthday,
            "typo": identifyNum,
            "sarcling": name,
            "storyitious": "11",
            "vitr": RandomStringGenerator.generate()
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/menaster",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<NetworkManager.Temp>.self, from: data)
                    DispatchQueue.main.async {
                        complation?(true, response.motherling, nil)
                        print("保存用户身份信息成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(true, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("保存用户身份信息失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(false, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    static func fetchConsumerInfo(productId: Int,
                                  _ complation: Complation<CustomerData>?) {
        let parameters: [String: Any] = [
            "caulithoughose": "\(productId)"
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/culturalally",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<CustomerData>.self, from: data)
                    DispatchQueue.main.async {
                        guard let customerData = response.myx else {
                            complation?(nil, response.motherling, "failed")
                            return
                        }
                        complation?(customerData, response.motherling, nil)
                        print("获取用户信息成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(nil, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取用户信息失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(nil, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    static func fetchAddressInfo(productId: Int,
                                  _ complation: Complation<CountryAddress>?) {
        let parameters: [String: Any] = [
            "wear": RandomStringGenerator.generate(),
            "sociallike": RandomStringGenerator.generate()
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/secutcommunity",
            method: .get,
            parameters: parameters,
            contentType: .formUrlEncoded
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<CountryAddress>.self, from: data)
                    DispatchQueue.main.async {
                        guard let customerAddress = response.myx else {
                            complation?(nil, response.motherling, "failed")
                            return
                        }
                        complation?(customerAddress, response.motherling, nil)
                        print("获取地址成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(nil, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取地址失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(nil, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
//    static func fetchSaveConsumerInfo(productId: Int,
//                                      megaloplanesques: [Megaloplanesque],
//                                      _ complation: Complation<Bool>?) {
//        var parameters: [String: Any] = [
//            "caulithoughose": "\(productId)",
//        ]
//    
//        for megaloplanesque in megaloplanesques {
//            if let shotish = megaloplanesque.shotish,
//               let type = PersonalListCellType(rawValue: shotish),
//               let key = megaloplanesque.dipsiaization {
//               
//                switch type {
//                case .enum:
//                    if let storyitious = megaloplanesque.storyitious {
//                        parameters[key] = storyitious
//                    }
//                case .txt, .citySelect:
//                    if let familiose = megaloplanesque.familiose {
//                        parameters[key] = familiose
//                    }
//                }
//            }
//        }
//        
//        NetworkManager.shared.requestData(
//            domain: .api,
//            path: "/plan/vivation",
//            method: .post,
//            parameters: parameters,
//            contentType: .formUrlEncoded
//        ) { result in
//            switch result {
//            case .success(let data):
//                do {
//                    let decoder = JSONDecoder()
//                    let response = try decoder.decode(Response<NetworkManager.Temp>.self, from: data)
//                    DispatchQueue.main.async {
//                        guard response.myx != nil else {
//                            complation?(false, response.motherling, "failed")
//                            return
//                        }
//                        complation?(true, response.motherling, nil)
//                        print("获取用户信息成功: ")
//                    }
//                    print("Status: \(response.dipsiaization)")
//                } catch {
//                    DispatchQueue.main.async {
//                        complation?(false, "failed", "failed")
//                    }
//                    print("JSON 解析失败: \(error)")
//                }
//            case .failure(let error):
//                print("获取用户信息失败: \(error.localizedDescription)")
//                DispatchQueue.main.async {
//                    complation?(false, error.localizedDescription, error.localizedDescription)
//                }
//            }
//        }
//    }
    
    static func fetchContacts(productId: Int,
                              _ complation: Complation<ContactsData>?) {
        let parameters: [String: Any] = [
            "caulithoughose": "\(productId)",
            "monstratorderery": RandomStringGenerator.generate()
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/acceptitude",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<ContactsData>.self, from: data)
                    DispatchQueue.main.async {
                        guard let contactsData = response.myx else {
                            complation?(nil, response.motherling, "failed")
                            return
                        }
                        complation?(contactsData, response.motherling, nil)
                        print("获取联系人信息成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(nil, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取联系人信息失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(nil, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    static func fetchSaveContacts(productId: Int,
                                  contacts: [ContactsSeptenier],
                                  _ complation: Complation<Bool>?) {
        
        
        let parameters: [String: Any] = [
            "caulithoughose": "\(productId)",
            "myx": convertToCompactJSON(contacts)
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/nonagenent",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<NetworkManager.Temp>.self, from: data)
                    DispatchQueue.main.async {
                        complation?(true, response.motherling, nil)
                        print("保存联系人信息成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(false, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("保存联系人信息失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(false, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    // 转换函数 - 生成紧凑JSON字符串
    static func convertToCompactJSON(_ contacts: [ContactsSeptenier]) -> String {
        // 转换为字典数组
        let dictArray = contacts.map { contact in
            return [
                "forgetence": contact.forgetence ?? "",
                "sarcling": contact.sarcling ?? "",
                "worryage": contact.worryage ?? "",
                "backence": contact.backence ?? ""
            ]
        }
        
        // 使用默认选项生成紧凑JSON
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: dictArray)
            return String(data: jsonData, encoding: .utf8) ?? ""
        } catch {
            print("JSON转换错误: \(error)")
            return ""
        }
    }
    
    static func fetchBanksInfo(productId: Int,
                              _ complation: Complation<BankData>?) {
        let parameters: [String: Any] = [
            "caulithoughose": "\(productId)"
        ]
        NetworkManager.shared.requestData(
            domain: .api,
            path: "/plan/septenier",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        ) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(Response<BankData>.self, from: data)
                    DispatchQueue.main.async {
                        guard let bankData = response.myx else {
                            complation?(nil, response.motherling, "failed")
                            return
                        }
                        complation?(bankData, response.motherling, nil)
                        print("获取绑卡信息成功: ")
                    }
                    print("Status: \(response.dipsiaization)")
                } catch {
                    DispatchQueue.main.async {
                        complation?(nil, "failed", "failed")
                    }
                    print("JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取绑卡信息失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    complation?(nil, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
//    static func fetchSaveBanksInfo(productId: Int,
//                                   megaloplanesques: [Megaloplanesque],
//                                   _ complation: Complation<Bool>?) {
//
//        var parameters: [String: Any] = [
//            "caulithoughose": "\(productId)",
//        ]
//    
//        for megaloplanesque in megaloplanesques {
//            if let shotish = megaloplanesque.shotish,
//               let type = PersonalListCellType(rawValue: shotish),
//               let key = megaloplanesque.dipsiaization {
//               
//                switch type {
//                case .enum:
//                    if let storyitious = megaloplanesque.storyitious {
//                        parameters[key] = storyitious
//                    }
//                case .txt, .citySelect:
//                    if let familiose = megaloplanesque.familiose {
//                        parameters[key] = familiose
//                    }
//                }
//            }
//        }
//        
//        NetworkManager.shared.requestData(
//            domain: .api,
//            path: "/plan/storyitious",
//            method: .post,
//            parameters: parameters,
//            contentType: .formUrlEncoded
//        ) { result in
//            switch result {
//            case .success(let data):
//                do {
//                    let decoder = JSONDecoder()
//                    let response = try decoder.decode(Response<NetworkManager.Temp>.self, from: data)
//                    DispatchQueue.main.async {
//                        complation?(true, response.motherling, nil)
//                        print("提交绑卡信息成功: ")
//                    }
//                    print("Status: \(response.dipsiaization)")
//                } catch {
//                    DispatchQueue.main.async {
//                        complation?(false, "failed", "failed")
//                    }
//                    print("JSON 解析失败: \(error)")
//                }
//            case .failure(let error):
//                print("提交绑卡信息失败: \(error.localizedDescription)")
//                DispatchQueue.main.async {
//                    complation?(false, error.localizedDescription, error.localizedDescription)
//                }
//            }
//        }
//    }
//    
//    // 埋点
//    static func fetchUploadLocationTrackingInfo(locationInfo: LYLocationManager.LocationInfo,
//                                                _ complation: Complation<Bool>?) {
//  
//        let parameters: [String: Any] = [
//            "cognform": locationInfo.province ?? "",
//            "heavy": locationInfo.countryCode ?? "",
//            "tricless": locationInfo.country ?? "",
//            "soundette": locationInfo.street ?? "",
//            "particularence": locationInfo.latitude,
//            "logcoaching": locationInfo.longitude,
//            "rhachia": locationInfo.city ?? "",
//            "plangtion": RandomStringGenerator.generate(),
//            "layful": locationInfo.district ?? ""
//        ]
//        NetworkManager.shared.requestData(
//            domain: .api,
//            path: "/plan/juxtaette",
//            method: .post,
//            parameters: parameters,
//            contentType: .formUrlEncoded
//        ) { result in
//            switch result {
//            case .success(let data):
//                do {
//                    let decoder = JSONDecoder()
//                    let response = try decoder.decode(Response<NetworkManager.Temp>.self, from: data)
//                    DispatchQueue.main.async {
//                        complation?(true, response.motherling, nil)
//                        print("上传位置信息成功: ")
//                    }
//                    print("Status: \(response.dipsiaization)")
//                } catch {
//                    DispatchQueue.main.async {
//                        complation?(false, "failed", "failed")
//                    }
//                    print("JSON 解析失败: \(error)")
//                }
//            case .failure(let error):
//                print("上传位置信息失败: \(error.localizedDescription)")
//                DispatchQueue.main.async {
//                    complation?(false, error.localizedDescription, error.localizedDescription)
//                }
//            }
//        }
//    }
//    
//    static func fetchUploadDeviceInfo(_ complation: Complation<Bool>?) {
//        
//        var dic: [String: Any] = [:]
//        
//        let nothlessDic: [String: Any] = [
//            "tersward": LYDeviceInfo.getStorage()?.free ?? -1,
//            "culturaly": LYDeviceInfo.getStorage()?.total ?? -1,
//            "doxoern": LYDeviceInfo.getSystemMemory().total,
//            "veraciarian": LYDeviceInfo.getSystemMemory().free
//        ]
//        
//        dic["nothless"] = nothlessDic
//        
//        let leucDic: [String: Any] = [
//            "everythingitive": Int(LYDeviceInfo.getBatteryInfo().level * 100),
//            "hippuous": RandomStringGenerator.generate(),
//            "reddefensekin": (LYDeviceInfo.getBatteryInfo().isCharging ? 1 : 0)
//        ]
//        
//        dic["leuc"] = leucDic
//        
//        let novelDic: [String: Any] = [
//            "fove": LYDeviceInfo.systemVersion,
//            "carry": "iPhone",
//            "federal": LYDeviceInfo.modelCode,
//            "vovaster": LYDeviceInfo.getDeviceInfo()?.name ?? "",
//            "tacture": SCREEN_HEIGHT,
//            "dooribility": SCREEN_WIDTH,
//            "uponmost": LYDeviceInfo.getDeviceInfo()?.measure ?? ""
//        ]
//        
//        dic["novel"] = novelDic
//        dic["rusability"] = RandomStringGenerator.generate()
//        
//        let mentcostastDic: [String: Any] = [
//            "foreignair": 100,
//            "word": "0",
//            "jugtoughia": LYDeviceInfo.isSimulator(),
//            "rumpance": LYDeviceInfo.isJailbroken(),
//            "backous": RandomStringGenerator.generate(),
//        ]
//        
//        dic["mentcostast"] = mentcostastDic
//
//        let openDic: [String: Any] = [
//            "memoryen": LYDeviceInfo.timezoneID,
//            "thatage": LYDeviceInfo.isUsingProxy,
//            "quartar": LYDeviceInfo.isUsingVPN(),
//            "cinerknowledgeier": LYDeviceInfo.carrierName,
//            "forceless": idfv,
//            "economic": LYDeviceInfo.deviceLanguage,
//            "importantative": RandomStringGenerator.generate(),
//            "mens": RandomStringGenerator.generate(),
//            "pariable": LYDeviceInfo.networkType,
//            "lex": LYDeviceInfo.isPhone,
//            "cruality": LYDeviceInfo.ipAddress,
//            "onceition": LYDeviceInfo.macAddress,
//            "meriitious": LYIDFAManager.shared.getCurrentIDFA() ?? ""
//        ]
//        
//        dic["open"] = openDic
//        
//        let locationManager = LYLocationManager.shared
//        var plumblyDic: [String: Any] = [:]
//        locationManager.getCurrentWifiInfo { info in
//            let agentyDic: [String: Any] = [
//                "emulive": info?.bssid ?? "" ,
//                "phonoaneity": info?.ssid ?? "",
//                "onceition": info?.bssid ?? "",
//                "sarcling": info?.ssid ?? "",
//                "experienceature": RandomStringGenerator.generate()
//            ]
//            plumblyDic["agenty"] = [agentyDic]
//            dic["plumbly"] = plumblyDic
//            
//            let parameters:[String: Any] = [
//                "myx": dictionaryToBase64(dict: dic) ?? ""
//            ]
//            NetworkManager.shared.requestData(
//                domain: .api,
//                path: "/plan/menaciability",
//                method: .post,
//                parameters: parameters,
//                contentType: .formUrlEncoded
//            ) { result in
//                switch result {
//                case .success(let data):
//                    do {
//                        let decoder = JSONDecoder()
//                        let response = try decoder.decode(Response<NetworkManager.Temp>.self, from: data)
//                        DispatchQueue.main.async {
//                            complation?(true, response.motherling, nil)
//                            print("上传设备信息成功: ")
//                        }
//                        print("Status: \(response.dipsiaization)")
//                    } catch {
//                        DispatchQueue.main.async {
//                            complation?(false, "failed", "failed")
//                        }
//                        print("JSON 解析失败: \(error)")
//                    }
//                case .failure(let error):
//                    print("上传设备信息失败: \(error.localizedDescription)")
//                    DispatchQueue.main.async {
//                        complation?(false, error.localizedDescription, error.localizedDescription)
//                    }
//                }
//            }
//        }
//    }
//    
//    static func fetchUploadGoogleMarket(_ complation: Complation<GoogleMarketData>?) {
//        let parameters:[String: Any] = [
//            "forceless": idfv,
//            "amphioon": RandomStringGenerator.generate(),
//            "meriitious": LYIDFAManager.shared.getCurrentIDFA() ?? ""
//        ]
//        NetworkManager.shared.requestData(
//            domain: .api,
//            path: "/plan/auctproof",
//            method: .post,
//            parameters: parameters,
//            contentType: .formUrlEncoded
//        ) { result in
//            switch result {
//            case .success(let data):
//                do {
//                    let decoder = JSONDecoder()
//                    let response = try decoder.decode(Response<GoogleMarketData>.self, from: data)
//                    DispatchQueue.main.async {
//                        
//                        guard let googleMarketData = response.myx else {
//                            complation?(nil, response.motherling, "failed")
//                            return
//                        }
//                        complation?(googleMarketData, response.motherling, nil)
//                        print("上传goole market成功: ")
//                    }
//                    print("Status: \(response.dipsiaization)")
//                } catch {
//                    DispatchQueue.main.async {
//                        complation?(nil, "failed", "failed")
//                    }
//                    print("JSON 解析失败: \(error)")
//                }
//            case .failure(let error):
//                print("上传goole market失败: \(error.localizedDescription)")
//                DispatchQueue.main.async {
//                    complation?(nil, error.localizedDescription, error.localizedDescription)
//                }
//            }
//        }
//    }
//    
//    static func fetchUploadRiskInfo(sceneType: SceneType,
//                                    productId: Int?,
//                                    orderNum: String?,
//                                    startTimeStamp: Double,
//                                    endTimeStamp: Double,
//                                    _ complation: Complation<Bool>?) {
//        let parameters:[String: Any] = [
//            "historylike": productId == nil ? "" : "\(productId!)",
//            "marketist": sceneType.rawValue,
//            "backable": orderNum ?? "",
//            "accordinging": idfv,
//            "carryeur": LYIDFAManager.shared.getCurrentIDFA() ?? "",
//            "logcoaching": LYUserDefaults.shared.getDouble(forKey: latitudeKey) ?? "",
//            "particularence": LYUserDefaults.shared.getDouble(forKey: longitudeKey) ?? "",
//            "octonice": "\(Int(startTimeStamp))",
//            "town": "\(Int(endTimeStamp))",
//        ]
//        NetworkManager.shared.requestData(
//            domain: .api,
//            path: "/plan/haloator",
//            method: .post,
//            parameters: parameters,
//            contentType: .formUrlEncoded
//        ) { result in
//            switch result {
//            case .success(let data):
//                do {
//                    let decoder = JSONDecoder()
//                    let response = try decoder.decode(Response<NetworkManager.Temp>.self, from: data)
//                    DispatchQueue.main.async {
//                        complation?(true, response.motherling, nil)
//                        print("上传风控埋点成功: ")
//                    }
//                    print("Status: \(response.dipsiaization)")
//                } catch {
//                    DispatchQueue.main.async {
//                        complation?(false, "failed", "failed")
//                    }
//                    print("JSON 解析失败: \(error)")
//                }
//            case .failure(let error):
//                print("上传风控埋点失败: \(error.localizedDescription)")
//                DispatchQueue.main.async {
//                    complation?(false, error.localizedDescription, error.localizedDescription)
//                }
//            }
//        }
//    }
//    
//    static func fetchUploadContactsInfo(myx: String, _ complation: Complation<Bool>?) {
//        let parameters:[String: Any] = [
//            "storyitious": "3",
//            "plicatthoughling": RandomStringGenerator.generate(),
//            "recentlyable": RandomStringGenerator.generate(),
//            "myx": myx
//        ]
//        NetworkManager.shared.requestData(
//            domain: .api,
//            path: "/plan/passerency",
//            method: .post,
//            parameters: parameters,
//            contentType: .formUrlEncoded
//        ) { result in
//            switch result {
//            case .success(let data):
//                do {
//                    let decoder = JSONDecoder()
//                    let response = try decoder.decode(Response<NetworkManager.Temp>.self, from: data)
//                    DispatchQueue.main.async {
//                        complation?(true, response.motherling, nil)
//                        print("上传通讯录埋点成功: ")
//                    }
//                    print("Status: \(response.dipsiaization)")
//                } catch {
//                    DispatchQueue.main.async {
//                        complation?(false, "failed", "failed")
//                    }
//                    print("JSON 解析失败: \(error)")
//                }
//            case .failure(let error):
//                print("上传通讯录埋点失败: \(error.localizedDescription)")
//                DispatchQueue.main.async {
//                    complation?(false, error.localizedDescription, error.localizedDescription)
//                }
//            }
//        }
//    }
}

// 定义数据模型
struct Response<T: Codable>: Codable {
    let dipsiaization: Int  // Changed to Int type
    let motherling: String
    let myx: T?
    
    enum CodingKeys: String, CodingKey {
        case dipsiaization
        case motherling
        case myx
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        // 处理可能的类型转换
        dipsiaization = try {
            if let intValue = try? container.decode(Int.self, forKey: .dipsiaization) {
                return intValue
            }
            let stringValue = try container.decode(String.self, forKey: .dipsiaization)
            guard let intValue = Int(stringValue) else {
                throw DecodingError.dataCorruptedError(
                    forKey: .dipsiaization,
                    in: container,
                    debugDescription: "Cannot convert dipsiaization to Int"
                )
            }
            return intValue
        }()
        
        motherling = try container.decode(String.self, forKey: .motherling)
        myx = try container.decodeIfPresent(T.self, forKey: .myx)
    }
}

//enum SceneType : String {
//    case signIn = "1"
//    case IdCredential = "2"
//    case faceCredential = "3"
//    case personalCredential = "4"
//    case contactCredential = "6"
//    case bankCredential = "7"
//    case startLoan = "8"
//    case endLoan = "9"
//}
